<template>
    <div class="page page-update">
        <!-- 版本 -->
        <div class="version">
            <div class="version-item version-type" v-if="globalVersion.versionName">
                <span>{{globalVersion.versionName}}</span>
            </div>
            <div class="version-item version-number" v-if="localHighestVersion.length">
                <span>V{{localHighestVersionStr}}</span>
            </div>
        </div>
        <!-- LOGO -->
        <div class="logo">
            <img class="logo-image" src="../assets/images/public/logo.svg"/>
            <div class="logo-text">{{globalVersion.title}}</div>
        </div>
        <!-- 启动中 -->
        <div class="state-item state-startingup" v-show="updateState==='startingUp'">
            <div class="state-item-text">启动中···</div>
        </div>
        <!-- 时间错误 -->
        <div class="state-item state-timeerror" v-show="updateState==='timeError'">
            <div class="state-item-text">当前系统时间与北京时间相差较大，请修改后重试！</div>
            <div class="state-item-btns">
                <x-button type="primary" @click="changeTime">修改时间</x-button>
                <x-button type="primary" @click="retry">重试</x-button>
            </div>
        </div>
        <!-- 启动失败 -->
        <div class="state-item state-startuperror" v-show="updateState==='startupError'">
            <div class="state-item-text">
                <i class="fa fa-info-circle"></i>
                {{updateStateMessage}}
            </div>
            <div class="state-item-btns">
                <x-button type="primary" @click="reload">重新加载</x-button>
            </div>
        </div>
        <!-- 正在更新/安装 -->
        <div class="state-item state-updating" v-show="['updating', 'installing'].includes(updateState)">
            <template v-if="updateState==='updating' && percent!==100">
                <div class="progress-wrapper">
                    <cmpProgress :percent="percent"></cmpProgress>
                </div>
                <div class="state-item-text">正在更新，请耐心等待···</div>
            </template>
            <div v-else-if="updateState==='installing'" class="state-item-btns">
                <x-button v-show="showSkipBtn" @click="skipInstallation">暂不安装</x-button>
                <x-button type="primary" @click="immediateInstallation">立即安装</x-button>
            </div>
        </div>
        <!-- 下载失败 -->
        <div class="state-item state-downloaderror" v-show="updateState==='downloadError'">
            <div class="state-item-text">
                <i class="fa fa-times-circle"></i>
                {{updateStateMessage}}
            </div>
            <div class="state-item-btns">
                <x-button type="primary" @click="reload">重新加载</x-button>
            </div>
        </div>
        <!-- 拖拽条 -->
        <div class="dragbar"></div>
        <!-- 关闭按钮 -->
        <div class="btn-close" @click="close">
            <i class="fa fa-close" ></i>
        </div>
        <!-- 关闭弹出框 -->
        <cmpMessageBox ref="cmpMessageBox" title="提示" :mask-closable="false">
            <div slot="body" class="msgbox-body-content">
                <div class="text-center">
                    程序正在运行中，确认退出吗？
                </div>
            </div>
            <div slot="footer" class="text-center">
                <x-button type="brown" size="small" @click="closeCancel" plain>取消</x-button>
                <x-button type="brown" size="small" @click="closeComfirm">确定</x-button>
            </div>
        </cmpMessageBox>
    </div>
</template>
<script>
import cmpProgress from '@/components/cmp-progress.vue'
import cmpMessageBox from '@/components/cmp-message-box.vue'
import globalVersion from '@/../public/version/index.js'
const fs = global.require('fs')
const path = global.require('path')
const { spawn } = global.require('child_process')
const { ipcRenderer, remote } = global.require('electron')

export default {
    name: 'update',
    components: {
        cmpProgress,
        cmpMessageBox
    },
    data(){
        return {
            globalVersion,
            updateState: 'startingUp', // 当前状态：startingUp/startupError/updating/installing/downloadError/timeError
            percent: 0, // 进度条数值
            appPackageName: '', // exe安装包的名字
            updateStateMessage: '',
            showSkipBtn: false,
            mainVersion: [], // 核心版本
            localHighestVersion: [], // 本地最高版本
        }
    },
    mounted () {
        setTimeout(() => {
            this.localHighestVersion = this.getLocalVersion()
            this.init()
        }, 3000)
    },
    computed:{
        localHighestVersionStr () {
            return this.localHighestVersion.join('.');
        }
    },
    methods:{
        // 对比用户本地时间和客户端打包时间
        checkTime () {
            // 用户本地时间
            let localTime = new Date().getTime()
            // 打包时间 - 24小时
            let publishTime = new Date(globalVersion.publishTime).getTime() - 24 * 60 * 60 * 1000
            // 对比本地时间和打包时间
            if (localTime >= publishTime) { // 可以正常启动
                this.init()
            } else { // 本地时间不对
                this.updateState = 'timeError'
            }
        },
        // 修改系统时间
        changeTime () {
            spawn('rundll32.exe', ['shell32.dll,Control_RunDLL', 'timedate.cpl'])
        },
        // 重试
        retry () {
            remote.app.relaunch()
            remote.app.exit(0)
        },
        // 重新加载
        reload () {
            this.updateState = 'startingUp'
            this.init()
        },
        // 暂不安装
        skipInstallation () {
            if (this.$jstools.compareVersions(this.localHighestVersion,this.mainVersion) !== 'equal') {
                this.runMain({
                    version: '',
                    path: path.join(this.$sharedObject('appsPath'), `app-${globalVersion.versionType}-v${this.localHighestVersion.join('.')}`),
                })
            } else {
                this.runMain({ version: '', path: '' })
            }
        },
        // 立即安装
        immediateInstallation () {
            ipcRenderer.send('update-app',path.join(this.$sharedObject('appsPath'), this.appPackageName))
        },
        // 关闭窗口
        close () {
            this.$refs.cmpMessageBox && this.$refs.cmpMessageBox.show()
        },
        // 关闭窗口 - 确定
        closeComfirm () {
            this.$refs.cmpMessageBox && this.$refs.cmpMessageBox.close()
            ipcRenderer.send('quit-app')
        },
        // 关闭窗口 - 取消
        closeCancel () {
            this.$refs.cmpMessageBox && this.$refs.cmpMessageBox.close()
        },
        // 跳转到主进程
        runMain (options) {
            ipcRenderer.send('create-main', options)
        },
        init () {
            let { getVal } = this.$sharedObject('electronSettingsPack')
            let appUpdateInfo = getVal(globalVersion.name, 'appUpdateInfo') || {}
            let localHighestVersion = this.localHighestVersion.slice(0, 3)
            let lastestMainVersion = [0, 0, 0]
            let lastestSmallVersion = [0, 0, 0]
            let appPackageLastest = appUpdateInfo.appPackageLastest || {}
            let appPackageH5Lastest = appUpdateInfo.appPackageH5Lastest || {}
            if (appPackageLastest.version) {
                lastestMainVersion = appPackageLastest.version.split('.')
                let filepath = new window.URL(appPackageLastest.url).pathname
                let ext = path.extname(filepath)
                let filename = `app-${globalVersion.versionType}-v${lastestMainVersion.join('.')}${ext}`
                appPackageLastest.ext = ext
                appPackageLastest.filename = filename
                appPackageLastest.localUrl = path.join(this.$sharedObject('appsPath'), filename)
            }
            if (appPackageH5Lastest.version) {
                lastestSmallVersion = appPackageH5Lastest.version.split('.')
                let filepath = new window.URL(appPackageH5Lastest.url).pathname
                let ext = path.extname(filepath)
                let filename = `app-${globalVersion.versionType}-v${lastestSmallVersion.join('.')}${ext}`
                appPackageH5Lastest.ext = ext
                appPackageH5Lastest.filename = filename
                appPackageH5Lastest.localUrl = path.join(this.$sharedObject('appsPath'), filename)
            }
            let mainFlag = this.$jstools.compareVersions(lastestMainVersion, localHighestVersion)
            let smallFlag = this.$jstools.compareVersions(lastestSmallVersion, localHighestVersion)
            if (mainFlag.slice(0, 3) === 'big' && fs.existsSync(appPackageLastest.localUrl)) {
                this.appPackageName = appPackageLastest.filename
                this.updateState = 'installing' // 出现安装按钮
                this.showSkipBtn = (appPackageLastest.updateType !== 'FORCED')
            } else if (smallFlag.slice(0, 3) === 'big' && fs.existsSync(appPackageH5Lastest.localUrl)) {
                let from = path.join(this.$sharedObject('appsPath'), appPackageH5Lastest.filename)
                let to = path.join(this.$sharedObject('appsPath'), appPackageH5Lastest.filename.slice(0, -1 * appPackageH5Lastest.ext.length))
                ipcRenderer.sendSync('update-main-unzip', {
                    from, to,
                    callback: () => {
                        this.runMain({
                            version: lastestSmallVersion,
                            path: to,
                            data: appPackageH5Lastest
                        })
                    }
                })
            } else {
                this.skipInstallation()
            }
        },
        // 获取本地最新版本
        getLocalVersion () {
            let codeVersion = globalVersion.version
            let settingsVersionKey = `smallVersion` // settings中记录的版本号Key
            let settingsVersionStr = `version`
            let { hasKey, getVal } = this.$sharedObject('electronSettingsPack')
            // 没有存过settings
            if (!hasKey(settingsVersionStr, settingsVersionKey)) {
                this.mainVersion = codeVersion
                return codeVersion
            }
            // 存过settings
            let settingsVersion = getVal(settingsVersionStr, settingsVersionKey)
            if (hasKey(settingsVersionStr, `mainVersion`)) {
                this.mainVersion = getVal(settingsVersionStr, `mainVersion`)
            } else {
                this.mainVersion = settingsVersion
            }
            if (this.$jstools.compareVersions(settingsVersion, codeVersion).substr(0,3) === 'big') {
                return settingsVersion
            } else {
                return codeVersion
            }
        }
    }
}
</script>
<style lang="less" scoped>
@import "~@/assets/css/_mixins.less";
@import "~@/assets/css/_color.less";
.page-update {
    background:#fff url("~@/assets/images/public/start-up.png") no-repeat center/cover;
    overflow: hidden;
    position: relative;
    .version {
        position: absolute;
        top:10px;
        left:10px;
        height: 20px;
        line-height: 20px;
        font-size: 12px;
        color: #fff;
        display: flex;
        flex-direction: row;
        .version-item {
            padding: 0 5px;
            &.version-type { background: rgba(101,121,254, 0.6); }
            &.version-number { background: rgba(216,101,241, 0.6); }
            &:first-child{
                border-top-left-radius: 5px;
                border-bottom-left-radius: 5px;
            }
            &:last-child{
                border-top-right-radius: 5px;
                border-bottom-right-radius: 5px;
            }
        }
    }
    .logo {
        margin-top: 30px;
        text-align: center;
        .logo-image {
            width: 75px;
            height: 75px;
        }
        .logo-text {
            margin-top: 20px;
            height: 22px;
            line-height: 22px;
            font-size:22px;
            color:#fff;
            user-select: none;
        }
    }
    .state-item {
        margin-top: 150px;
        text-align: center;
        .state-item-text {
            font-size: 16px;
            line-height: 1.5;
            letter-spacing: .2em;
        }
        .state-item-btns {
            margin-top: 20px;
            .x-button { width: 120px; margin: 0 10px; }
        }
    }
    .state-startingup {
        .state-item-text { color:#00bbac; }
    }
    .state-timeerror {
        .state-item-text { color:#ec4015; }
    }
    .state-startuperror {
        .state-item-text { color:#657180; }
    }
    .state-updating {
        .progress-wrapper {
            width: 70%;
            margin: 0 auto;
        }
        .state-item-text { color:#657180; }
    }
    .state-downloaderror {
        .state-item-text { color:#00bbac; }
    }
    .btn-close{
        position: absolute;
        top: 5px;
        right: 6px;
        width: 30px;
        height: 30px;
        font-size: 20px;
        border-radius: 50%;
        cursor: pointer;
        -webkit-app-region: no-drag;
        color: rgba(0,0,0,0.4);
        .flex-center;
        &:hover {
            color: #fff;
            background-color: #75a24d;
        }
    }
    .dragbar {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 50px;
        -webkit-app-region: drag;
    }
    .fa-info-circle,
    .fa-times-circle { color: #ff9a57; }
}
.cmp-message-box {
    .msgbox-body-content {
        height: 100%;
        .flex-center;
    }
    .x-button {
        margin: 0 10px;
    }
}
</style>
